import React, { useState, useEffect } from 'react';
import { message, Drawer, Form, Button, Row, Col, TreeSelect, Input, Spin } from 'antd';
import local from '@/utils/local';
import { useModel } from 'umi';

import { addField, upadataField, cmsColumnDept, cmsColumnAllTree, cmsSiteAllTree } from '../api';
import styles from '../index.less';

const { SHOW_ALL } = TreeSelect;
/**
 * @zh-CN 部门同步树
 *
 * @param datas
 */

const setTreeFormat = datas => {
  const newData = [];

  datas.map(item => {
    const obj = {
      id: item.deptId,
      value: item.deptId,
      pId: item.parentId,
      title: item.deptName,
    };
    if (item.children && item.children.length) {
      obj.children = setTreeFormat(item.children);
    }
    newData.push(obj);
    return '';
  });
  return newData;
};
/**
 * @zh-CN 栏目同步树格式化
 *
 * @param datas
 */

const setColumnTreeFormat = datas => {
  const newData = [];
  datas.map(item => {
    const obj = {
      id: item.columnId,
      value: item.columnId,
      pId: item.parentId,
      title: item.columnName,
    };
    if (item.children && item.children.length) {
      obj.children = setColumnTreeFormat(item.children);
    }
    newData.push(obj);
    return '';
  });
  return newData;
};

/**
 * @zh-CN 站点同步树
 *
 * @param datas
 */

const setSiteTreeFormat = datas => {
  const newData = [];
  datas.map(item => {
    const obj = {
      id: item.siteId,
      value: item.siteId,
      pId: item.parentId,
      title: item.siteName,
    };
    if (item.children && item.children.length) {
      obj.children = setSiteTreeFormat(item.children);
    }
    newData.push(obj);
    return '';
  });
  return newData;
};

const UpdateForm = props => {
  // 结构化数据
  const { visible, onCancel, onSuccess, data, type } = props;

  // 初始化 form
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const [dept, setDept] = useState(); //  部门值
  const [sysDeptAllTreeData, setSysDeptAllTreeData] = useState(); // 部门同步树

  const [column, setColumn] = useState(); //  栏目
  const [cmsColumnAllTreeData, setcmsColumnAllTreeData] = useState(); // 栏目同步树

  const [site, setSite] = useState(); //  站点
  const [cmsSiteAllTreeData, setcmsSiteAllTreeData] = useState(); // 站点同步树

  // const { initialState } = useModel('@@initialState');
  // const currentDeptId = initialState?.currentUser?.sysUserVo?.deptId;

  // 栅格化
  const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 14 },
  };

  // 详情
  const getDetailData = () => {
    setDept(data.deptIds);
    getSysDeptAllTree(data.siteId);
    form.setFieldsValue({ siteName: data.siteName, columnName: data.columnName });
  };
  /**
   * @zh-CN 同步获取部门树
   *
   * @param fields
   */
  const getSysDeptAllTree = async fields => {
    setLoading(true);
    try {
      const res = await cmsColumnDept(fields);
      setLoading(false);
      if (res.code === 0) {
        setSysDeptAllTreeData(setTreeFormat([res.data]));
        return;
      }
    } catch (error) {
      setLoading(false);
      message.error('获取部门失败，请重试');
      return false;
    }
  };

  /**
   * @zh-CN 同步获取栏目树
   *
   * @param fields
   */
  const getcmsColumnAllTree = async fields => {
    setLoading(true);
    try {
      const res = await cmsColumnAllTree(fields);
      setLoading(false);
      if (res.code === 0) {
        setcmsColumnAllTreeData(setColumnTreeFormat(res.data));
        return;
      }
      setcmsColumnAllTreeData([]);
    } catch (error) {
      setLoading(false);
      message.error('获取栏目失败，请重试');
      return false;
    }
  };

  /**
   * @zh-CN 同步获取站点树
   *
   * @param fields
   */
  const getCmsSiteAllTree = async fields => {
    try {
      const data = await cmsSiteAllTree({ ...fields });
      if (data.code === 0) {
        setcmsSiteAllTreeData(setSiteTreeFormat([data.data]));
        return;
      }
    } catch (error) {
      message.error('获取站点失败，请重试');
      return false;
    }
  };

  // 选择部门
  const deptOnChange = value => {
    setDept(value);
  };
  // 选择站点
  const siteOnChange = value => {
    setSite(value);
    setColumn();
    setDept();
    getSysDeptAllTree(value);
    getcmsColumnAllTree(value);
  };
  // 选择栏目
  const columnOnChange = value => {
    setColumn(value);
  };

  useEffect(() => {
    setDept();
    setColumn();
    setSite();
    setSysDeptAllTreeData([]);
    if (type === 'updata' && visible === true) {
      getDetailData();
    } else {
      if (!cmsSiteAllTreeData && visible) {
        getCmsSiteAllTree();
      }
      form.resetFields();
    }
  }, [visible]);

  const accessToken = local.get('token');

  /**
   * @en-US Update node
   * @zh-CN values
   *
   * @param fields
   */
  const updataData = values => {
    const hide = message.loading('正在添加');
    setLoading(true);
    upadataField({
      ...values,
    }).then(res => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || '修改失败，请重试');
      }
    });
  };
  /**
   * @en-US Update node
   * @zh-CN 添加
   *
   * @param values
   */
  const addData = values => {
    const hide = message.loading('正在添加');
    setLoading(true);
    addField({ ...values }).then(res => {
      hide();
      setLoading(false);
      if (res.code === 0) {
        onCancel(false);
        onSuccess();
      } else {
        message.error(res.msg || '添加失败，请重试');
      }
    });
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param values
   */
  const sendData = () => {
    form.validateFields().then(values => {
      values.deptId = dept;
      if (type === 'add') {
        values.columnId = column;
      }
      if (type === 'updata') {
        values.columnId = data.columnId;
      }
      if (type === 'updata') updataData(values);
      if (type === 'add') addData(values);
    });
  };

  const modelClose = () => {
    onCancel(false);
  };

  return (
    <>
      <Drawer
        getContainer={false}
        width={640}
        title={type === 'updata' ? '修改' : '添加'}
        visible={visible}
        onClose={modelClose}
        maskClosable={false}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Button onClick={modelClose} style={{ marginRight: 10 }}>
              取消
            </Button>
            <Button onClick={sendData} type="primary" loading={loading} disabled={loading}>
              保存
            </Button>
          </div>
        }
      >
        <Spin spinning={loading}>
          <Form {...formItemLayout} name="control-ref" form={form}>
            {visible && type === 'add' && (
              <div className={styles.treeBox}>
                <Row>
                  <Col span={14} push={4}>
                    <TreeSelect
                      treeData={cmsSiteAllTreeData}
                      placeholder="选择站点"
                      value={site}
                      style={{ width: 340 }}
                      // multiple
                      showSearch
                      // treeDefaultExpandAll
                      onChange={(value, label, extra) => {
                        siteOnChange(value, label, extra);
                      }}
                      allowClear
                    />
                  </Col>
                  <Col span={4} pull={14}>
                    <div className={styles.treeName}>
                      <em className="star">*</em>选择站点：
                    </div>
                  </Col>
                </Row>
              </div>
            )}
            {type === 'updata' && (
              <Form.Item label="站点" name="siteName">
                <Input maxLength={100} allowClear placeholder="" disabled={true} />
              </Form.Item>
            )}
            {visible && type === 'add' && (
              <div className={styles.treeBox}>
                <Row>
                  <Col span={14} push={4}>
                    <TreeSelect
                      treeData={cmsColumnAllTreeData}
                      placeholder="先选择站点，再选择栏目"
                      value={column}
                      style={{ width: 340 }}
                      showSearch
                      onChange={(value, label, extra) => {
                        columnOnChange(value, label, extra);
                      }}
                      allowClear
                    />
                  </Col>
                  <Col span={4} pull={14}>
                    <div className={styles.treeName}>
                      <em className="star">*</em>选择栏目：
                    </div>
                  </Col>
                </Row>
              </div>
            )}

            {type === 'updata' && (
              <Form.Item label="栏目" name="columnName">
                <Input maxLength={100} allowClear placeholder="" disabled={true} />
              </Form.Item>
            )}
            {visible && (
              <div className={styles.treeBox}>
                <Row>
                  <Col span={14} push={4}>
                    <TreeSelect
                      treeData={sysDeptAllTreeData}
                      placeholder="选择部门"
                      value={dept}
                      showCheckedStrategy={SHOW_ALL}
                      style={{ width: 340 }}
                      allowClear
                      multiple
                      showSearch
                      treeCheckable={true}
                      // treeDefaultExpandAll
                      onChange={(value, label, extra) => {
                        deptOnChange(value, label, extra);
                      }}
                    />
                  </Col>
                  <Col span={4} pull={14}>
                    <div className={styles.treeName}>
                      <em className="star">*</em>选择部门：
                    </div>
                  </Col>
                </Row>
              </div>
            )}
          </Form>
        </Spin>
      </Drawer>
    </>
  );
};

export default UpdateForm;
